<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:">
                        <el-select
                            name="fundCode"
                            v-model="orderForm.fundCode"
                            size="mini"
                            @change="handleFormChange($event, 'fundCode')"
                            filterable
                            clearable
                        >
                            <el-option
                                v-for="i in fundCodeSelectData"
                                :key="i.fundCode"
                                :label="i.fundCode + ' ' + i.fundNameSt"
                                :value="i.fundCode"
                                :name="'fundCode' + i.fundCode + orderDirection"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="资产单元编号:" v-show="SHOW_SECURITY">
                        <el-select v-model="orderForm.assetCode" size="mini">
                            <el-option
                                v-for="i in computedAssetCodeSelectData"
                                :key="i.assetCode"
                                :label="i.assetCode + ' ' + i.assetName"
                                :value="i.assetCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="组合编码:">
                        <el-select
                            name="组合编码"
                            v-model="orderForm.fundAccountCode"
                            size="mini"
                            @change="handleFormChange($event, 'fundAccountCode')"
                        >
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                :value="i.fundAccountCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证券代码:">
                        <el-select
                            name="证券代码"
                            size="mini"
                            clearable
                            filterable
                            :filter-method="queryMarginTradingStockLists"
                            v-model="orderForm.stockCode"
                            @clear="handleStockCodeClear"
                            @change="handleFormChange($event, 'stockCode')"
                            @visible-change="handleVisibleChange"
                        >
                            <el-option
                                v-for="(i, index) in stockCodeSelectData"
                                :key="i.stockCode + index"
                                :label="orderDirection !== 'C' ? i.stockCode + ' ' + i.stockNameSt : i.stockCode + ' ' + i.stockName"
                                :value="i.stockCode"
                                :name="'stockCode' + i.stockCode + orderDirection"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select name="业务类型" v-model="orderForm.businessType" size="mini" disabled>
                            <el-option value="x" label="融资融券信用业务"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="委托方向:">
                        <el-select
                            v-if="!['1', '2'].includes(orderDirection)"
                            name="委托方向"
                            v-model="orderForm.orderDirection"
                            size="mini"
                            :class="['font-color-' + textColor]"
                            :disabled="true"
                        >
                            <el-option
                                v-for="i in orderDirectionSelectData1"
                                :key="i.dictKey"
                                :label="i.dictKeyName"
                                :value="i.dictKey"
                                :name="'orderDirection' + i.dictKey"
                            >
                            </el-option>
                        </el-select>

                        <el-select
                            v-else
                            name="委托方向"
                            v-model="orderForm.orderDirection"
                            size="mini"
                            :class="['font-color-' + textColor]"
                            @change="handleFormChange($event, 'orderDirection')"
                        >
                            <el-option
                                v-for="i in orderDirectionSelectData2"
                                :key="i.dictKey"
                                :label="i.dictKeyName"
                                :value="i.dictKey"
                                :style="handleOptionColor(i.dictKey)"
                                :name="'orderDirection' + i.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="目标类型:" v-if="!SHOW_SECURITY">
                        <el-select name="目标类型" v-model="orderForm.targetType" size="mini">
                            <el-option
                                v-for="(value, key) in targetTypePojo"
                                :key="key"
                                :label="value"
                                :value="key"
                                :name="'targetType' + key + orderDirection"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="价格模式:">
                        <el-select v-model="orderForm.orderPriceType" size="mini" disabled>
                            <!-- <el-option value="1" label="限价"></el-option>
                            <el-option value="2" label="市价"></el-option> -->
                            <el-option
                                v-for="i in investPriceSelectData"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="当前市价:" class="icon-form-item">
                        <RiskInputNumber
                            :input="orderForm.closePrice"
                            :inputAfter="'元'"
                            :precision="2"
                            :maxlength="14"
                            :colorStyle="textColor"
                            :field="'closePrice'"
                            :disabled="true"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                        <i class="el-icon-refresh-right" @click="getMarketPriceByStockCode(orderForm.stockCode, '1')"></i>
                    </el-form-item>
                    <el-form-item label="指令价格:">
                        <RiskInputNumber
                            :input="orderForm.orderPrice"
                            :inputAfter="'元'"
                            :precision="2"
                            :maxlength="14"
                            :colorStyle="textColor"
                            :field="'orderPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="指令数量:">
                        <RiskInputNumber
                            :readonly="!orderForm.stockCode"
                            :disabled="orderForm.targetType == '2'"
                            :input="orderForm.orderAmount"
                            :inputAfter="'股'"
                            :maxlength="14"
                            :field="'orderAmount'"
                            :colorStyle="textColor"
                            :precision="0"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="指令金额:">
                        <RiskInputNumber
                            :disabled="orderForm.targetType == '1'"
                            :input="orderForm.orderBalance"
                            :inputAfter="'元'"
                            :precision="2"
                            :maxlength="14"
                            :field="'orderBalance'"
                            :colorStyle="textColor"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="目标类型:" v-if="SHOW_SECURITY">
                        <el-select name="目标类型" v-model="orderForm.targetType" size="mini">
                            <el-option
                                v-for="(value, key) in targetTypePojo"
                                :key="key"
                                :label="value"
                                :value="key"
                                :name="'targetType' + key + orderDirection"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { getBusinessType } from '../api';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { getMarketPrice } from '@/common/api/instruction';
import {
    queryMarginTradingFunds,
    queryMarginTradingPosiotions,
    queryMarginTradingStocks,
    queryPermissionFunds,
    querySubsStock,
} from '../api/margin-trading';
import { convertNum, getConfigItem, handleInverseAmount, handleLimitAmount, handleTextColor, uniqueFunc } from '@/utils/tools';
import LayoutHeader from '@/layout/layout-header.vue';

@Component({
    name: 'MarginTradingForm',
    components: {
        RiskInputNumber,
        RiskEntryInput,
    },
})
// 融资买入、融券卖出、担保券买卖、融资融券申购指令表单
export default class MarginTradingForm extends Vue {
    @Prop()
    orderDirection: string; // 默认选中委托方向
    @Prop()
    tableSelectedStockInfo: any; // 表格选中的证券信息
    @Prop()
    refreshNumber: number;
    handleOptionColor = handleTextColor;

    selectedStockInfo: any = null; // 下拉框选中的证券信息
    // 指令表单
    orderForm = {
        fundCode: '', // 产品代码
        assetCode: '',
        assetName: '',
        fundAccountCode: '', // 组合编码
        orderDirection: '', // 委托方向
        stockCode: '', // 证券代码
        stockNameSt: '', // 证券名称
        reportCode: '', // 申报代码
        marketCode: '', // 交易市场编码
        businessType: 'x', // 业务类型
        businClass: 'x',
        orderPriceType: '2', // 价格模式
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        closePrice: '', // 当前市价
        fundNameSt: '', // 产品简称
        fundAccountName: '', // 组合名称
        targetType: '1',
    };
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    investPriceSelectData: any[] = []; // 价格模式下拉数据
    stockCodeSelectData: any[] = []; // 证券代码下拉数据
    // 委托方向下拉数据
    orderDirectionSelectData1: any[] = [
        {
            dictKey: '{',
            dictKeyName: '融资买入',
        },
        {
            dictKey: '[',
            dictKeyName: '融券卖出',
        },
        {
            dictKey: '}',
            dictKeyName: '卖券还款',
        },
        {
            dictKey: ']',
            dictKeyName: '买券还券',
        },
        {
            dictKey: 'C',
            dictKeyName: '申购',
        },
    ];
    // 担保券买卖--委托方向下拉数据
    orderDirectionSelectData2: any[] = [
        {
            dictKey: '1',
            dictKeyName: '买入',
        },
        {
            dictKey: '2',
            dictKeyName: '卖出',
        },
    ];

    fundCodeWithPermission: any[] = []; // 根据权限查询的产品
    fundCodeWithAssetUnit: any[] = []; // 包含资产单元为融资融券信用资产单元的基金列表
    textColor: string = ''; // 表单字体颜色
    marketPrice: string = ''; // 当前市价
    orderPrice: string = ''; // 实际指令价格
    pages = { currentPage: 1, pageSize: 25 };
    fundCodeSelectData: any[] = [];
    selectLoading: boolean = false;
    targetTypePojo: any = {}; // 目标类型枚举对象
    changeFlag: string = '';
    changeflagPojo = {
        '{': '1',
        '[': '2',
        '}': '2',
        ']': '1',
        C: '1',
        '1': '1',
        '2': '2',
    };

    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    // 监听 资产单元计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedAssetCodeSelectData', { immediate: true, deep: true })
    watchcomputedAssetCode(newData) {
        if (!this.SHOW_SECURITY) {
            return;
        }
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.assetCode == this.orderForm.assetCode);
            obj = d1 || newData[0];
        }
        this.orderForm.assetCode = obj.assetCode;
        this.orderForm.assetName = obj.assetName;

        this.$emit('getOrderForm', this.orderForm);
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item['fundAccountCode'] == this.orderForm['fundAccountCode']);
            obj = d1 || newData[0];
        }
        this.orderForm.assetCode = obj.assetCode;
        this.orderForm.assetName = obj.assetName;
        this.orderForm.fundAccountCode = obj.fundAccountCode;
        this.orderForm.fundAccountName = obj.fundAccountName;
        this.$emit('getOrderForm', this.orderForm);
    }

    get computedAssetCodeSelectData(): any {
        return uniqueFunc(this.fundAccountCodeSelectData[this.orderForm.fundCode], 'assetCode');
    }

    // 组合编码下拉框计算属性;
    get computedFundAccountCodeSelectData() {
        let data = this.fundAccountCodeSelectData[this.orderForm.fundCode];
        let retData = [];
        if (data && this.SHOW_SECURITY) {
            const obj = data.filter(item => item.assetCode == this.orderForm.assetCode);
            retData = obj || [];
        } else {
            retData = data;
        }
        return retData;
    }

    // // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    // @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    // watchcomputedFundAccountCode(newData) {
    //     if (newData && newData.length) {
    //         this.orderForm.fundAccountCode = newData[0].fundAccountCode;
    //     } else {
    //         this.orderForm.fundAccountCode = '';
    //     }
    //     this.$emit('getOrderForm', this.orderForm);
    // }

    // 监听表格选中的证券信息
    @Watch('tableSelectedStockInfo', { immediate: true, deep: true })
    watchSelectedStockInfo(newData, oldData) {
        if (JSON.stringify(newData) !== JSON.stringify(oldData) && this.tableSelectedStockInfo) {
            this.orderForm.stockCode = this.tableSelectedStockInfo?.stockCode;
            this.orderForm.reportCode = this.tableSelectedStockInfo?.reportCode;
            this.orderForm.marketCode = this.tableSelectedStockInfo?.marketNo;
            this.orderForm.stockNameSt = this.tableSelectedStockInfo?.stockNameSt;
            if (this.orderDirection === 'C') {
                // 融资融券申购：申购价格默认显示价格下限的值
                this.orderForm.orderPrice = this.tableSelectedStockInfo?.lowerPrice;
                this.orderForm.stockNameSt = this.selectedStockInfo?.stockName;
                this.orderForm.orderPriceType = '1';
            }
            if (this.tableSelectedStockInfo?.stockCode) {
                this.getMarketPriceByStockCode(this.tableSelectedStockInfo?.stockCode, '2');
            }

            this.$emit('getOrderForm', this.orderForm);
            // 设置下拉框证券代码选中
            this.selectedStockInfo = JSON.parse(JSON.stringify(this.tableSelectedStockInfo));
            this.queryMarginTradingStockLists(this.orderForm.stockCode);
        }
    }

    @Watch('orderDirection', { immediate: true, deep: true })
    onWatchOrderDirection() {
        // 设置默认委托方向
        this.orderForm.orderDirection = this.orderDirection;
        this.orderForm.closePrice = '';
        // this.orderForm.stockCode = '';
        this.handlePriceChange(this.orderForm.orderPrice);
        // this.handleTextColor(this.orderDirection);
        // this.queryMarginTradingStockLists('');
        this.handleOrderDirectionChange(this.orderDirection);
    }

    async mounted() {
        // 获取目标类型
        this.targetTypePojo = DictionConstUtil.targetType;
        // 价格模式下拉数据
        this.investPriceSelectData = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        this.queryfundList();
        // 获取组合编码下拉框数据
        let arr = await DictionConstUtil.FNFundAccount();
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
    }

    @Watch('refreshNumber', { immediate: true })
    onWatchRefreshNumber() {
        if (this.refreshNumber && this.orderForm.stockCode) {
            this.getMarketPriceByStockCode(this.orderForm.stockCode, '2');
        }
    }

    // 子组件事件传递--数字输入框组件
    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];

        this.orderForm[field] = value;
        this.handleFormChange(value, field);
    }

    // 处理表单变化
    handleFormChange(value: string, field: string) {
        if (field === 'stockCode') {
            this.handleStockCodeChange(value);
        } else if (field === 'fundCode') {
            this.handleFundCodeChange(value);
        } else if (field === 'orderDirection') {
            this.handleOrderDirectionChange(value);
            // this.handleTextColor(value);
        } else if (field === 'orderPrice') {
            this.handlePriceChange(value);
        } else if (field === 'orderAmount') {
            setTimeout(() => {
                this.handleAmountChange(value);
            }, 10);
            // this.handleAmountChange(value);
        } else if (field === 'orderBalance') {
            this.handleOrderBalanceChange();
        }

        this.$emit('getOrderForm', this.orderForm);
    }

    handleVisibleChange(state: boolean) {
        if (!state && !this.stockCodeSelectData.length) {
            this.queryMarginTradingStockLists('');
        }
    }

    handleFundCodeChange(fundCode: string) {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === fundCode) || {};
        this.orderForm.fundNameSt = fund.fundNameSt;
        // 卖券还款与卖出的时候可选证券代码与产品相关联
        if (['}', '2'].includes(this.orderDirection)) {
            this.queryMarginTradingStockLists('');
            this.orderForm.stockCode = '';
            this.orderForm.stockNameSt = '';
            this.orderForm.reportCode = '';
            this.orderForm.closePrice = '';
            this.selectedStockInfo = {};
            this.$emit('getStockInfo', this.selectedStockInfo);
        }
    }

    handleOrderDirectionChange(orderDirection: string) {
        this.orderForm.stockCode = '';
        this.orderForm.stockNameSt = '';
        this.orderForm.reportCode = '';
        this.selectedStockInfo = {};
        this.$emit('getStockInfo', this.selectedStockInfo);
        this.queryMarginTradingStockLists(this.orderForm.stockCode);
        this.handleTextColor(orderDirection);
        if (orderDirection) {
            this.changeFlag = this.changeflagPojo[orderDirection];
        } else {
            this.changeFlag = '';
        }
    }

    handlePriceChange(price: string) {
        let orderBalance = '';
        // 修改指令价格
        if (this.orderForm.orderPrice) {
            // 根据输入值计算
            this.orderForm.orderPriceType = '1';
            this.orderPrice = this.orderForm.orderPrice;
            if (this.orderForm.orderAmount) {
                // 如果没有金额只有数量，计算金额就行
                orderBalance = (Number(this.orderForm.orderAmount || '0') * Number(this.orderForm.orderPrice || '0')).toFixed(2);
            } else {
                // 金额数量都是空，不做处理
            }
        } else {
            this.orderForm.orderPriceType = '2';
            if (this.orderForm.closePrice) {
                if (this.orderForm.orderBalance) {
                    if (this.orderForm.targetType == '1') {
                        // 绝对数量算金额
                        orderBalance = (Number(this.orderForm.orderAmount || '0') * Number(this.orderForm.closePrice || '0')).toFixed(2);
                    } else if (this.orderForm.targetType == '2') {
                        // 绝对金额反推数量
                        this.orderForm.orderAmount = (Number(this.orderForm.orderBalance || '0') / Number(this.orderForm.closePrice || '0')).toFixed(
                            0
                        );
                        this.orderForm.orderAmount = handleInverseAmount(this.changeFlag, this.selectedStockInfo, this.orderForm.orderAmount);
                        orderBalance = this.orderForm.orderBalance;
                    }
                } else if (this.orderForm.orderAmount) {
                    if (this.orderForm.targetType == '1') {
                        // 如果没有金额只有数量，计算金额就行
                        orderBalance = (Number(this.orderForm.orderAmount || '0') * Number(this.orderForm.closePrice || '0')).toFixed(2);
                    }
                } else {
                    // 金额数量都是空，不做处理
                }
            } else {
            }
        }
        let inputLength = 0;
        if (convertNum(String(orderBalance)) === false) {
            if (orderBalance && orderBalance !== '0.00') {
                this.yh_message_warn('指令金额整数位长度超出14');
                orderBalance = '';
            }
        } else {
            if (orderBalance.includes('.')) {
                inputLength = orderBalance.split('.')[0].length;
            } else {
                inputLength = orderBalance.length;
            }
            if (inputLength > 14) {
                this.yh_message_warn('指令金额整数位长度超出14');
                orderBalance = '';
            }
        }
        this.orderForm.orderBalance = orderBalance;
    }

    handleAmountChange(value) {
        if (value.toString() == '0') {
            this.yh_message_warn('指令数量必须大于0！');
            this.orderForm.orderAmount = '';
            return;
        }
        let orderAmount = '';
        // 限定指令数量
        let limit = handleLimitAmount(this.changeFlag, this.selectedStockInfo, value);
        if (!limit) {
            this.orderForm.orderAmount = orderAmount;
        }

        let orderBalance = '';
        if (this.orderForm.orderPriceType === '1') {
            orderBalance = (Number(this.orderForm.orderPrice || '0') * Number(this.orderForm.orderAmount || '0')).toString();
        } else {
            orderBalance = (Number(this.orderForm.closePrice || '0') * Number(this.orderForm.orderAmount || '0')).toString();
        }

        let inputLength = 0;
        if (convertNum(String(orderBalance)) === false) {
            if (orderBalance && orderBalance !== '0') {
                this.yh_message_warn('指令金额整数位长度超出14');
                orderBalance = '';
            }
        } else {
            if (orderBalance.includes('.')) {
                inputLength = orderBalance.split('.')[0].length;
            } else {
                inputLength = orderBalance.length;
            }
            if (inputLength > 14) {
                this.yh_message_warn('指令金额整数位长度超出14');
                orderBalance = '';
            }
        }

        this.orderForm.orderBalance = orderBalance;
    }

    handleOrderBalanceChange() {
        let orderAmount: any = '';
        // 根据金额反推数量，取整
        if (this.orderForm.orderPriceType == '1') {
            if (Number(this.orderForm.orderBalance || '0') && this.orderForm.orderPrice) {
                // this.orderForm.orderAmount = parseInt(
                //     (Number(this.orderForm.orderBalance) / Number(this.orderForm.orderPrice)).toString()
                // ).toString();
                orderAmount = Number(this.orderForm.orderBalance) / Number(this.orderForm.orderPrice);
                if (String(orderAmount).indexOf('e-') !== -1) {
                    this.orderForm.orderAmount = '0';
                } else {
                    this.orderForm.orderAmount = parseInt(orderAmount).toString();
                }
            } else {
                this.orderForm.orderAmount = '';
            }
        } else {
            if (Number(this.orderForm.orderBalance || '0') && this.orderForm.closePrice) {
                orderAmount = Number(this.orderForm.orderBalance) / Number(this.orderForm.closePrice);
                if (String(orderAmount).indexOf('e-') !== -1) {
                    this.orderForm.orderAmount = '0';
                } else {
                    this.orderForm.orderAmount = parseInt(orderAmount).toString();
                }
            } else {
                this.orderForm.orderAmount = '';
            }
        }
        this.orderForm.orderAmount = handleInverseAmount(this.changeFlag, this.selectedStockInfo, this.orderForm.orderAmount);
    }

    handleStockCodeChange(stockCode: string) {
        if (stockCode) {
            this.selectedStockInfo = this.stockCodeSelectData.find(item => item.stockCode === stockCode);
            this.orderForm.marketCode = this.selectedStockInfo?.marketNo;
            this.orderForm.reportCode = this.selectedStockInfo?.reportCode;
            this.orderForm.stockNameSt = this.selectedStockInfo?.stockNameSt;
            if (this.orderDirection === 'C') {
                this.orderForm.orderPrice = this.selectedStockInfo?.lowerPrice;
                this.orderForm.stockNameSt = this.selectedStockInfo?.stockName;
                this.orderForm.orderPriceType = '1';
            }
            this.$emit('getStockInfo', this.selectedStockInfo);
            // 获取当前市价
            this.getMarketPriceByStockCode(stockCode, '2');
        } else {
            this.orderForm.closePrice = '';
            this.orderForm.marketCode = '';
            this.orderForm.reportCode = '';
            this.orderForm.stockNameSt = '';
            if (this.orderDirection === 'C') {
                this.orderForm.orderPrice = '';
                this.handlePriceChange(this.orderForm.orderPrice);
                this.orderForm.orderPriceType = '2';
            }
        }
    }

    // 证券代码清空事件处理
    handleStockCodeClear() {
        this.selectedStockInfo = {};
        this.queryMarginTradingStockLists('');
        this.handlePriceChange(this.orderForm.orderPrice);
        this.$emit('getStockInfo', this.selectedStockInfo);
    }

    // 根据委托方向处理字段颜色
    handleTextColor(orderDirection: string) {
        if (['{', '1', 'C', ']'].includes(orderDirection)) {
            this.textColor = 'red';
        } else if (['[', '}', '2'].includes(orderDirection)) {
            this.textColor = 'green';
        } else {
            this.textColor = '';
        }
    }

    // 根据证券代码获取当前市价 type: 1-手动刷新(点击刷新图标)，2-自动刷新(切换证券时), 3-点击试算刷新
    getMarketPriceByStockCode(stockCode: string, type: any) {
        if (!stockCode) {
            return;
        }
        getMarketPrice(stockCode)
            .then((res: any) => {
                if (res !== undefined) {
                    this.orderForm.closePrice = res.toString();
                } else {
                    this.orderForm.closePrice = '0';
                }
                if (this.orderForm.orderPriceType == '2') {
                    this.handlePriceChange(this.orderForm.closePrice);
                }
                if (type == '1') {
                    setTimeout(() => {
                        this.yh_message_success('“当前市价”已刷新！');
                    }, 10);
                }

                this.$emit('getOrderForm', this.orderForm);
            })
            .catch(err => {
                this.orderForm.closePrice = '0';
                this.$emit('getOrderForm', this.orderForm);
                this.yh_message_error(err);
            });
    }

    // 查询包含资产单元为融资融券信用资产单元且符合用户权限的基金列表
    queryfundList() {
        Promise.all([queryMarginTradingFunds(), queryPermissionFunds('')])
            .then(res => {
                this.fundCodeWithAssetUnit = res[0];
                this.fundCodeWithPermission = res[1];
                this.fundCodeWithAssetUnit.forEach(item => {
                    this.fundCodeWithPermission.forEach(ele => {
                        if (ele.fundCode === item.fundCode) {
                            this.fundCodeSelectData.push(item);
                        }
                    });
                });
            })
            .catch(err => {
                this.yh_message_error(err);
            });
    }

    // 查询证券代码
    queryMarginTradingStockLists(val: string | undefined) {
        let type = '';
        switch (this.orderForm.orderDirection) {
            case '1':
                type = '1';
                this.queryStockCodeList(val, type);
                break;
            case '{':
                type = '2';
                this.queryStockCodeList(val, type);
                break;
            case '[':
                type = '3';
                this.queryStockCodeList(val, type);
                break;
            case '2':
            case '}':
                type = '1';
                this.queryPositionList(val, type);
                // this.queryMarginTradingPosiotionList(val);
                break;
            case 'C':
                this.queryPurchaseStocks(val);
                break;
            case ']':
                type = '3';
                this.queryPositionList(val, type);
                break;
            default:
                break;
        }
    }

    // 查询融资融券标的券、担保券
    queryStockCodeList(val: string | undefined, type: string) {
        this.selectLoading = true;
        queryMarginTradingStocks({
            sort: '',
            stockNameOrCode: val,
            type: type,
            paging: this.pages,
        })
            .then((res: any) => {
                this.stockCodeSelectData = res.list || [];
                this.selectLoading = false;
            })
            .catch(err => {
                this.selectLoading = false;
                this.yh_message_error(err);
            });
    }

    // 查询担保券持仓、融券标的券持仓
    queryPositionList(val: string | undefined, type: string) {
        this.selectLoading = true;
        queryMarginTradingPosiotions({
            sort: '',
            stockNameOrCode: val,
            type: type,
            paging: this.pages,
            fundCode: type === '1' ? this.orderForm.fundCode : '',
        })
            .then((res: any) => {
                this.stockCodeSelectData = res.list || [];
                this.selectLoading = false;
            })
            .catch(err => {
                this.selectLoading = false;
                this.yh_message_error(err);
            });
    }

    // 查询可申购证券
    queryPurchaseStocks(val: string | undefined) {
        this.selectLoading = true;
        querySubsStock({
            sort: '',
            stockNameOrCode: val,
            paging: this.pages,
        })
            .then((res: any) => {
                this.stockCodeSelectData = res.list || [];
                this.selectLoading = false;
            })
            .catch(err => {
                this.selectLoading = false;
                this.yh_message_error(err);
            });
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';
</style>
